package com.ship.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtils;
import com.ship.common.core.utils.poi.ExcelUtil;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysDept;
import com.ship.system.api.domain.SysFile;
import com.ship.system.api.domain.SysUserNew;
import com.ship.system.domain.SysBindPerms;
import com.ship.system.domain.SysMenu;
import com.ship.system.domain.SysUserDept;
import com.ship.system.domain.dto.SysDataBindDto;
import com.ship.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色及权限管理
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/user/permission")
@Api(value = "sysUserPermission", tags = "用户角色及权限管理")
public class SysUserMenuController
{
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserDeptService userDeptService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserNewService userNewService;

    @Value("${file_server.host}")
    private String fileServerHost;

    @Resource
    private RemoteFileService remoteFileService;

    /**
     * 获取部门树信息
     */
    @ApiOperation(value = "获取部门树信息")
    @PostMapping("/dept/tree")
    public JsonResult deptTree(@RequestBody SysDept dept)
    {
        return JsonResult.success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取菜单下拉树信息
     */
    @ApiOperation(value = "获取菜单下拉树信息")
    @PostMapping("/menu/tree")
    public JsonResult menuTree(@RequestBody SysMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return JsonResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 岗位授权菜单权限
     */
    @ApiOperation(value = "岗位授权菜单权限")
    @Log(title = "部门管理", businessType = BusinessType.GRANT)
    @PostMapping("/auth/menu")
    public JsonResult insertAuthMenu(@RequestBody SysDataBindDto dto)
    {
        if(dto.getDataId() == null || dto.getBindList() == null){
            return JsonResult.failed("参数异常！");
        }
        deptService.insertDeptAuthMenu(dto.getDataId(), dto.getBindList());
        return JsonResult.success();
    }

    /**
     * 获取用户分页信息
     */
    @ApiOperation(value = "获取用户分页信息")
    @PostMapping("/userPage")
    public JsonResult<Page<SysUserNew>> getUserPage(@RequestBody SysUserNew user)
    {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(user.getDeptId() != null){
            //传入了部门id则查询该部门及其子部门下的用户数据
            List<SysDept> deptList = deptService.selectDeptAndChildList(user.getDeptId());
            if(deptList.size() == 0){
                return JsonResult.success(new Page<>());
            }
            List<Long> deptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            String deptSearch = deptIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            user.setDeptIdListForSearch(deptSearch);
        }
        user.setOrderField("user_id");
        user.setDeptId(null);
        Page<SysUserNew> page = userNewService.page(user, queryWrapper);
        for (SysUserNew userNew : page.getList()) {
            userNew.setIsAdmin(userNew.getUserId() != null && 1L == userNew.getUserId());
            deptService.resetUserPostInfo(userNew);
        }
        return JsonResult.success(page);
    }

    /**
     * 获取用户列表信息
     */
    @ApiOperation(value = "获取用户列表信息")
    @PostMapping("/userList")
    public JsonResult<List<SysUserNew>> getUserList(@RequestBody SysUserNew user)
    {
        QueryWrapper<SysUserNew> queryWrapper = new QueryWrapper<>();
        if(user.getDeptId() != null){
            //传入了部门id则查询该部门及其子部门下的用户数据
            List<SysDept> deptList = deptService.selectDeptAndChildList(user.getDeptId());
            if(deptList.size() == 0){
                return JsonResult.success(new LinkedList<>());
            }
            List<Long> deptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            String deptSearch = deptIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            user.setDeptIdListForSearch(deptSearch);
        }
        user.setOrderField("user_id");
        user.setDeptId(null);
        if(StringUtils.isNotBlank(user.getUserOrNickNameSearch())){
            queryWrapper.and(wrapper -> wrapper.like("user_name",user.getUserOrNickNameSearch())
                    .or().like("nick_name", user.getUserOrNickNameSearch()));
        }
        List<SysUserNew> userList = userNewService.pageExportList(user, queryWrapper, new LinkedList<>());
        for (SysUserNew userNew : userList) {
            userNew.setIsAdmin(userNew.getUserId() != null && 1L == userNew.getUserId());
            deptService.resetUserPostInfo(userNew);
        }
        return JsonResult.success(userList);
    }

    @ApiOperation(value = "用户导出")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/userPage/export")
    public JsonResult export(@RequestBody SysUserNew user)
    {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(user.getDeptId() != null){
            //传入了部门id则查询该部门及其子部门下的用户数据
            List<SysDept> deptList = deptService.selectDeptAndChildList(user.getDeptId());
            if(deptList.size() == 0){
                return JsonResult.success(new Page<>());
            }
            List<Long> deptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            String deptSearch = deptIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            user.setDeptIdListForSearch(deptSearch);
        }
        user.setOrderField("user_id");
        user.setDeptId(null);
        if (CollectionUtil.isNotEmpty(user.getIds())){
            queryWrapper.in("user_id",user.getIds());
        }
        List<SysUserNew> list = userNewService.pageExportList(user, queryWrapper,new LinkedList<>());
        for (SysUserNew userNew : list) {
            userNew.setIsAdmin(userNew.getUserId() != null && 1L == userNew.getUserId());
            if(userNew.getUpdateTime() != null){
                userNew.setUpdateTimeFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",userNew.getUpdateTime()));
            }
            deptService.resetUserPostInfo(userNew);
        }
        ExcelUtil<SysUserNew> util = new ExcelUtil<SysUserNew>(SysUserNew.class);
        MultipartFile file = util.getExportExcelUrl(list, "用户数据",fileServerHost);
        if(file == null){
            return JsonResult.failed("文件解析失败！");
        }
        R<SysFile> result = remoteFileService.upload(file);
        if(result.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        return JsonResult.success(result.getData().getHttpsUrl());
    }

    /**
     * 用户授权岗位
     */
    @ApiOperation(value = "用户授权岗位")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/auth/dept")
    public JsonResult insertAuthDept(@RequestBody SysDataBindDto dto)
    {
        if(dto.getDataId() == null || dto.getBindList() == null){
            return JsonResult.failed("参数异常！");
        }
        userService.insertUserAuthDept(dto.getDataId(), dto.getBindList());
        return JsonResult.success();
    }

    /**
     * 用户绑定权限
     * @param sysBindPerms
     * @return
     */
    @ApiOperation(value = "用户绑定权限")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/bind/permissions")
    public JsonResult userBingMenu(@RequestBody SysBindPerms sysBindPerms){
        menuService.bindPerms(sysBindPerms);
        return JsonResult.success();
    }


}
